import React, { Component } from "react";
import Api from "../../../config/api";
import axios from "axios";
import styles from "./sass/market-send.scss";

import Button from "antd/lib/button";
import Input from "antd/lib/input";
import Form from "antd/lib/form";
import message from "antd/lib/message";
import Upload from "antd/lib/upload";

const FormItem = Form.Item;
const { TextArea } = Input;

class sendMsg extends Component {
  constructor(props) {
    super(props);
    this.state = {
      allAccount: [],
      loading: false,
      fileList: [],
      msgInfo:{
        count:'',
        dianXin:'',
        lianTong:'',
        unKnownCount:'',
        yiDong:'',
        phones:''
      },
      userInfo: JSON.parse(localStorage.getItem('userInfo')),
      userDetail:{}
    };
  }
  componentWillMount() {
    this.getUserInfo()
  }
  getUserInfo(){
    axios.post(Api["getAccountInfoByUser"] + `?account=${this.state.userInfo.account}`).then(res => {
      if (res) {
        if(res.data){
          this.setState({
            userDetail:res.data
          })
        }
        else{
          this.setState({
            userDetail:{
              smsNum:0
            }
          })
        }
      } else {
        this.setState({
          loading: false
        });
      }
    }).catch(function(error) {
      console.log(error);
      this.setState({
        loading: false
      });
    });
  }
  sendMessage(e) {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        if(this.state.msgInfo.count){
          let data = JSON.parse(JSON.stringify(values));
          data.phones = this.state.msgInfo.phones;
          data.account = this.state.userInfo.account;
          this.setState({
            loading: true
          });
          axios.post(Api["sendMessage"], data).then(res => {
              if (res) {
                message.success("提交成功");
                this.getUserInfo();
                this.props.form.resetFields(["content"]);
                this.setState({
                  fileList: [],
                  msgInfo:{},
                  loading: false
                });
              } else {
                this.setState({
                  loading: false
                });
              }
            })
            .catch(function(error) {
              console.log(error);
              this.setState({
                loading: false
              });
            });
        }else{
          message.error('号码总数不能为空');
        }
      }
    });
  }
  downloadTem(){
    document.location.href = Api['downloadTemplate'];
  }
  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 21 }
      }
    };
    const props = {
      name: "file",
      accept:'.csv',
      action: Api["importPhone"],
      headers: {
        authorization: "authorization-text"
      },
      onRemove: file => {
        this.setState({
          fileList: [],
          msgInfo:{}
        });
      },
      beforeUpload: file => {
        let arr = [file];
        this.setState({
          fileList: arr
        });
        let formData = new FormData();
        formData.append('file',file);
        axios.post(Api["importPhone"],formData).then(res => {
          if (res) {
            let data = JSON.parse(JSON.stringify(res.data));
            this.setState({
              msgInfo:data
            })
          } 
        })
        .catch(error => {
          console.log(error);
        });
        return false;
      },
      fileList: this.state.fileList
    };
    return (
      <div style={{height: 'calc(100vh - 150px)',overflow: 'auto'}}>
        <Form className={styles["form-box"]}>
          <FormItem label="账号" {...formItemLayout}>
            <Input value={this.state.userInfo.account} disabled />
          </FormItem>
          <FormItem label="余额" {...formItemLayout}>
            <Input value={this.state.userDetail.smsNum} disabled />
          </FormItem>
          <div style={{position:'relative'}}>
            <FormItem label="号码" {...formItemLayout}>
              {getFieldDecorator("phones", {validateFirst: true,rules: [{ required: true, message: "必须上传" }]})(
                <Upload {...props}>
                  <Button>导入号码</Button>
                </Upload>
                )}
            </FormItem>
            <a style={{position: 'absolute',right: '55%',top: '8px'}} onClick={this.downloadTem.bind(this)}>下载模板</a>
          </div>
          <FormItem label="统计" {...formItemLayout}>
            <span className={styles["send-phone-analyse-item"]}>总数：{this.state.msgInfo.count}</span>
            <span className={styles["send-phone-analyse-item"]}>移动：{this.state.msgInfo.yiDong}</span> 
            <span className={styles["send-phone-analyse-item"]}>联通：{this.state.msgInfo.lianTong}</span> 
            <span className={styles["send-phone-analyse-item"]}>电信：{this.state.msgInfo.dianXin}</span> 
            <span className={styles["send-phone-analyse-item"]}>未知：{this.state.msgInfo.unKnownCount}</span>             
          </FormItem>
          <FormItem label="内容" {...formItemLayout}>
            {getFieldDecorator("content", {validateFirst: true,rules: [{ required: true, message: "必填" }]})(
            <TextArea rows="6" placeholder="请输入内容" />
            )}
          </FormItem>
          <FormItem>
            <Button type="primary" onClick={this.sendMessage.bind(this)} className={styles["submit-btn"]} disabled={this.state.loading}>
              发送短信
            </Button>
          </FormItem>
        </Form>
      </div>
    );
  }
}

const ValidateForm = Form.create()(sendMsg);

export default ValidateForm;
